<script setup lang="ts">
import type { SelectBaseOption } from 'naive-ui/es/select/src/interface';

import { usePageDataStore } from '@/store/modules/page-data';
import type { BasicTreeSelectProps } from '@/components/form/src/components/tree-select/props';

defineOptions({
  name: 'BasicSelect',
});

const props = withDefaults(defineProps<BasicTreeSelectProps>(), {
  cascade: false,
  checkable: false,
  checkStrategy: 'all',
  childrenField: 'children',
  consistentMenuWidth: true,
  defaultExpandAll: true,
  disabled: false,
  keyField: 'id',
  labelField: 'label',
  disabledField: 'disabled',
  maxTagCount: 2,
  multiple: false,
  options: [] as any,
  placeholder: '请选择',
  size: 'medium',
  defaultFirst: false,
});

const emits = defineEmits<{
  (e: 'update:value', value: any[] | string | number | null): void;
}>();

const localValue = ref(props.value);
const options = ref(props.options);

watchImmediate(() => props.value, value => {
  localValue.value = value;
});

/**
 * 获取共享数据
 *
 * 注意：监听会执行两次 第二次在表单项v-modal中
 */
watchImmediate(() => props.shareDataKey, key => {
  if (key) {
    options.value = usePageDataStore().get<Recordable[]>(key) ?? [];
    if (props.defaultFirst) {
      localValue.value = options.value[0]?.[props.keyField] as any;
      emits('update:value', localValue.value ?? null);
    }
  }
});

function handleUpdateValue(
  value: any[] | string | number | null,
  _option: SelectBaseOption | null | SelectBaseOption[],
) {
  emits('update:value', value);
}
</script>

<template>
  <NTreeSelect
    :cascade="props.cascade"
    :checkable="props.checkable"
    :check-strategy="props.checkStrategy"
    :children-field="props.childrenField"
    :consistent-menu-width="props.consistentMenuWidth"
    :disabled="props.disabled"
    :key-field="props.keyField"
    :label-field="props.labelField"
    :disabled-field="props.disabledField"
    :max-tag-count="props.maxTagCount"
    :multiple="props.multiple"
    :options="options"
    :placeholder="props.placeholder"
    :value="localValue"
    :size="props.size"
    clearable
    filterable
    @update:value="handleUpdateValue"
  />
</template>

<style scoped lang="less">

</style>
